package com.sky.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.result.Result;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController("UserDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api("用户端菜品接口")
public class DishController {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id获取菜品
     * @return
     */
    @ApiOperation("根据分类id获取菜品")
    @GetMapping("/list")
    public Result<List<DishVO>> listById(Long categoryId){
        //构造redis中的key，规则： dish_ + categoryId
        String key="dish_"+categoryId;
        //查询redis中是否存在菜品数据
        List<DishVO> list= (List<DishVO>) redisTemplate.opsForValue().get(key);
        if(list!=null&&list.size()>0){
            //如果存在，则直接返回，无需查询数据库
            return Result.success(list);
        }
        //如果不存在，查询数据库，将查询到的数据存入redis中
        LambdaQueryWrapper<Dish> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId);
        lambdaQueryWrapper.eq(Dish::getStatus,1);
        List<Dish> dishes = dishService.list(lambdaQueryWrapper);
        //获取dish对应的口味
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper=new LambdaQueryWrapper<>();
        List<DishVO> dishVOList=new ArrayList<>();
        dishes.stream().map((dish)->{
            DishVO dishVO=new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishVO.setFlavors(dishFlavors);
            dishVOList.add(dishVO);
            return dish;
        }).collect(Collectors.toList());
        //将数据放到Redis中
        redisTemplate.opsForValue().set(key,dishVOList);
        return Result.success(dishVOList);
    }
}
